﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WordServices.HttpService;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace WordsOfLove.ForumPages
{
	/// <summary>
	/// An empty page that can be used on its own or navigated to within a Frame.
	/// </summary>
	public sealed partial class PostDetailsPage : Page
	{
		ForumPostInfo RelatedPost { get; set; }
		ObservableCollection<ForumCommentInfo> Comments { get; set; }

		public PostDetailsPage()
		{
			this.InitializeComponent();
			Comments = new ObservableCollection<ForumCommentInfo>();
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			base.OnNavigatedTo(e);
			if (!(e.Parameter is ForumPostInfo)) return;
			RelatedPost = e.Parameter as ForumPostInfo;
			TitleTxt.Text = RelatedPost.Title;
			DetailsTxt.Text = $"发布者：{RelatedPost.UserName} 发布于：{RelatedPost.CreateTime} 最后编辑于：{RelatedPost.UpdateTime}";
			ContentTxt.Text = RelatedPost.Content;
			LikeBtn.Content = $"赞({RelatedPost.CommentCount})";
			HttpUtils utils = HttpUtilsFactory.Utils;
			try
			{
				Comments = new ObservableCollection<ForumCommentInfo>(utils.SendGetJsonMessage<List<ForumCommentInfo>>($"api/ForumComment/GetComments?postId={RelatedPost.Id}"));
			}
			catch //(Exception ex)
			{
				new MessageDialog("服务器错误").ShowAsync();
			}
			if (RelatedPost.UserId == CurrentUserFactory.CurrentUserId)
			{
				EditBtn.Visibility = Visibility.Visible;
				DeleteBtn.Visibility = Visibility.Visible;
			} 
			else
			{
				EditBtn.Visibility = Visibility.Collapsed;
				DeleteBtn.Visibility = Visibility.Collapsed;
			}
			if (CurrentUserFactory.CurrentUser == null)
			{
				LikeBtn.IsEnabled = false;
				CommentBtn.IsEnabled = false;
			}
			RefreshLikeInfo();
			CommentListView.ItemsSource = Comments;
		}

		private void RefreshLikeInfo()
		{
			HttpUtils utils = HttpUtilsFactory.Utils;
			try
			{
				int LikeCount = utils.SendGetJsonMessage<int>($"api/ForumPost/GetLikeCount?postId={RelatedPost.Id}");
				bool Liked = utils.SendGetJsonMessage<ForumPostLike>($"api/ForumPost/GetLike?postId={RelatedPost.Id}&userId={CurrentUserFactory.CurrentUserId}") != null;
				LikeBtn.Content = (Liked ? "取消" : "赞") + $"({LikeCount})";
			}
			catch //(Exception ex)
			{
				new MessageDialog("服务器错误").ShowAsync();
			}
		}

		private void LikeBtn_Click(object sender, RoutedEventArgs e)
		{
			HttpUtils utils = HttpUtilsFactory.Utils;
			try
			{
				if((LikeBtn.Content as string).StartsWith("取消"))
				{
					utils.SendDeleteMessage($"api/ForumPost/DeleteLike?postId={RelatedPost.Id}&userId={CurrentUserFactory.CurrentUserId}");
				}
				else
				{
					utils.SendPutMessage($"api/ForumPost/CreateLike", new ForumPostLike()
					{ 
						PostId = RelatedPost.Id,
						UserId = CurrentUserFactory.CurrentUserId
					});
				}
				RefreshLikeInfo();
			}
			catch //(Exception ex)
			{
				new MessageDialog("服务器错误").ShowAsync();
			}
		}

		private void DeleteBtn_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				HttpUtils utils = HttpUtilsFactory.Utils;
				utils.SendDeleteMessage($"api/ForumPost/DeletePost?id={RelatedPost.Id}");
				if (Frame.CanGoBack) Frame.GoBack();
			}
			catch //(Exception ex)
			{
				new MessageDialog("服务器错误").ShowAsync();
			}
		}

		private void EditBtn_Click(object sender, RoutedEventArgs e)
		{
			this.Frame.Navigate(typeof(PostEditPage), RelatedPost);
		}

		private void CommentBtn_Click(object sender, RoutedEventArgs e)
		{
			HttpUtils utils = HttpUtilsFactory.Utils;
			CommentBox.TextDocument.GetText(Windows.UI.Text.TextGetOptions.AdjustCrlf, out string commentStr);
			try
			{
				utils.SendPostMessage("api/ForumComment/CreateComment", new ForumComment()
				{
					Content = commentStr,
					CreateTime = DateTime.Now,
					PostId = RelatedPost.Id,
					UserId = CurrentUserFactory.CurrentUserId
				});
				Comments = new ObservableCollection<ForumCommentInfo>(utils.SendGetJsonMessage<List<ForumCommentInfo>>($"api/ForumComment/GetComments?postId={RelatedPost.Id}"));
				CommentListView.ItemsSource = Comments;
			}
			catch //(Exception ex)
			{
				new MessageDialog("服务器错误").ShowAsync();
			}
		}
	}
}
